<?php

namespace App\Http\Controllers\home;

use App\Article as ArticleModel;
use App\Replies as RepliesModel;
use View;

class Article extends Base
{

    public function __construct()
    {
        parent::__construct();
        //1,判断是否有锚点
        $anchors = request()->get('anchors', false);

        //搜索条件
        $this->searchData['search_field']   = request()->get('search_field', '');
        $this->searchData['search_content'] = request()->get('search_content', '');

        //排序条件
        $this->sortData['sort_field'] = request()->get('sort_field', 'id');
        $this->sortData['sort_type']  = request()->get('sort_type', 'desc');
        $this->sortData['sort_type']  = $this->sortData['sort_type'] == 'desc' ? 'asc' : 'desc';
        View::share([
            'anchors'    => $anchors,
            'searchData' => $this->searchData,
            'sortData'   => $this->sortData,
        ]);
    }

    //文章列表
    public function index()
    {

        $searchData  = $this->searchData;
        $sortData    = $this->sortData;
        $articleList = ArticleModel::orderBy($sortData['sort_field'], $sortData['sort_type'])
            ->where(function ($query) use ($searchData) {
                //查询
                if ($searchData['search_field'] && $searchData['search_content']) {
                    if ($searchData['search_field'] == 'title') {
                        $query->where($searchData['search_field'], 'like', '%' . $searchData['search_content'] . '%');
                    } else {
                        $query->where($searchData['search_field'], '=', $searchData['search_content']);
                    }
                }
            })
            ->paginate(15);
        return view('home.index', [
            'articleList' => $articleList,

        ]);
    }

    public function detail($articleId = 0)
    {

        // 1,查出文章
        $articleInfo = ArticleModel::find($articleId);

        // 2,增加点击率
        $articleInfo::where('id', '=', $articleId)->increment('click', 1);

        // 3, 查出游客回复此文章的贴子
        $repliesList = RepliesModel::orderBy('id', 'desc')
            ->where('article_id', '=', $articleId)
            ->paginate(15);
        $repliesList->appends([
            'anchors' => true,
        ]);
        return view('home.detail', [
            'articleInfo' => $articleInfo,
            'repliesList' => $repliesList,
        ]);
    }
}
